<template>
  <div v-loading="loading">
    <b-table
      ref="table"
      :columns="columns"
      :scroll="{ x: 1300 }"
      :request="loadData"
      :export-config="{ use: true,select: '招标物资明细',all: '招标物资明细'}"
    >
      <template
        v-if="state !== 3"
        slot="prefix"
        slot-scope="ref"
      >
        <a-button
          :loading="addLoading"
          type="primary"
          @click="openDialog()"
        >
          添加行
        </a-button>
        <a-button @click="ref.delete(delFuc, delEnd)">
          删除行
        </a-button>
      </template>
      <template
        v-if="state !== 3"
        slot="suffix"
      >
        <!-- v-btn-permission="'lcm_003_exp_05'" -->
        <!-- <excel ref="exportBtn"
                file-name="招标物资明细"
                content-title="招标物资明细"
                is-click-generate="false"
              > -->
        <a-button
          slot="excelBtn"
          type="primary"
          icon="cloud-download"
          @click="openDialog(downloadApi)"
        >
          标准模板下载
        </a-button>
        <!-- </excel> -->
        <ExcelImportButton
          :loading="loadingImport"
          icon="import"
          button-text="批量导入"
          @handleSubmit="handleImport"
        />
      </template>
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['number', 'taxPrice','totalPrice']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="editable">
            <BaseInputNumber
              v-if="col === 'number'"
              v-model="record[col]"
              class="requiredFormItem"
              :class="record[col] ? '' : 'validateError'"
              :precision="3"
              :min="0"
              :disabled="col === 'totalPrice'"
              @blur="e => handleChange(record)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              class="requiredFormItem"
              :precision="2"
              :min="0"
              :disabled="col === 'totalPrice'"
              @blur="e => handleChange(record)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <material-list-and-dir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import { selectOption } from '@/api/material/goods/goods'
import { materialsList, materialsListDel, materialsAddList, materialsEdit, materialPurchaseApplyExcel } from '@/api/material/procurement/apply'
import { columns } from './insideModel'
import { planDetailEdit, planDetailList } from '@/api/material/procurement/plan'
import moment from 'moment'

const data = []
export default {
    name: 'RebarPlan',
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            openDialogType: 'add',
            loading: false,
            addLoading: false,
            loadingImport: false,
            loadData: params => materialsList({ ...params, purchaseApplyId: this.id }),
            delFuc: materialsListDel,
            downloadApi: materialPurchaseApplyExcel,

            columns: columns,
            data: this.tableData,
            rules: {
                number: { rule: 'required', message: '数量不能为空' },
                taxPrice: { rule: 'required', message: '市场含税价不能为空' }
            },
            editingIndex: null,
            checkedData: []
        }
    },
    computed: {
      editable() {
        return this.state !== 3
      }
    },
    watch: {},
    mounted: function() {
        if (this.state === 3) {
            this.editingIndex = null
        }
        this.initErrMessage(this.rules)
    },
    methods: {
        delEnd() {
          if (!this.$refs.table.tableData.length) {
            this.$refs.table.getData(null, true);
          };
        },
        createList: function(selectRowKeys) {
          this.loading = true
          const list = selectRowKeys.map((item, index) => {
            let params = {
                executeType: '0', // 0批量新增1批量导入
                materialName: item.name,
                materialCode: item.code,
                materialModel: item.specificationModel,
                unit: item.unitId,
                purchaseApplyId: this.id,
                number: '',
                taxPrice: '',
                totalPrice: '',
                materialId: item.id
            }
            return params;
          })
          materialsAddList(list).then(res => {
            this.loading = false
            if ((res.code === 200) || (res.data?.code === 200)) {
                this.$message.success('添加成功')
                this.cancel()
            }
          }).catch(() => {
            this.loading = false;
          })
        },
        async openDialog(downloadApi) {
            let checkedData = this.$refs.table.tableData;
            if (this.$refs.table.totalSize > 10) {
              this.addLoading = true;
              let res = await materialsList({
                pageSize: this.$refs.table.totalSize,
                pageNo: 1,
                purchaseApplyId: this.id,
              })
              
              checkedData = res.data;
              this.addLoading = false
              // this.$refs.detailDialog.open(checkedData)
            } else {
              // this.$refs.detailDialog.open(checkedData)
            }
            if (downloadApi){
              const fileName = "物资招标采购申请模板_" + moment(new Date()).format('YYYY-MM-DD') + ".xlsx";
              this.$refs.detailDialog.download(checkedData,downloadApi,fileName)
            }else {
              this.$refs.detailDialog.open(checkedData)
            }
        },
        handleChange(row) {
            if (Number(row['number']) &&  Number(row['taxPrice'])) {
              row['totalPrice'] = Number(row['number']) * Number(row['taxPrice'])
              row['taxPrice'] = Number(row['taxPrice']).toFixed(6)
              row['totalPrice'] = Number(row['totalPrice']).toFixed(6)
            }
            this.save(row);
        },
        async save(row) {
          let res = await materialsEdit(row)
          if (res.code === this.SUCCESS_CODE) {
            this.$emit('getTotalPrice')
          }else {
            this.$noticeWarning(res.message)
          }
        },
        cancel() {
            this.editingIndex = null
            this.$refs.table.getData(null, true)
        },
        /**
         * 导入
         */
        async handleImport(list) {
          console.log(list)
          try {
            if (this.loadingImport) return
            this.loadingImport = true;
            const columns = [
              {title: '物资名称',dataIndex: 'materialName'},
              {title: '物料编码',dataIndex: 'materialCode'},
              {title: '规格型号',dataIndex: 'materialModel'},
              {title: '单位',dataIndex: 'unit'},
              {title: '数量',dataIndex: 'number'},
              {title: '市场含税价',dataIndex: 'taxPrice'},
              // {title: '金额（元）',dataIndex: 'totalPrice'}
            ]
            const paramsList = []
            list &&
              list.forEach((item) => {
                const resultItem = {}
                for (const key in item) {
                  const target = columns.find((column) => column.title === key)
                  if (target) {
                      resultItem[target.dataIndex] = item[key]
                  }
                }
                resultItem.totalPrice = (!isNaN(Number(resultItem.number)) && (!isNaN(Number(resultItem.taxPrice))))
                                        ? (Number(resultItem.number) * Number(resultItem.taxPrice)).toFixed(6)
                                        : 0;
                resultItem.purchaseApplyId = this.id;
                resultItem.executeType = '1';
                paramsList.push(resultItem)
              })
            if (!paramsList.length) {
              this.$message.warning('请录入导入数据')
            }
            materialsAddList(paramsList).then(res => {
              this.loadingImport = false;
              if ((res.code === 200) || (res.data?.code === 200)) {
                  this.$message.success('导入成功')
                  this.cancel()
              }
            }).catch(() => {
              this.loadingImport = false;
            })
            // const res = await importPartyFeeRecords(paramsList)
            // this.loadingImport = false;
            // if ((res && res.code == 0) || (res && res.data && res.data.code == 0)) {
            //   const msg = res.msg || res.data.msg;
            //   this.$message.success(msg)
            //   this.$refs.table.refresh(true)
            // } else {
            //   this.$message.error('导入失败！')
            // }
          } catch (e) {
            this.loadingImport = false
          }
          
        }
    }
}
</script>
